package com.kedou.sdk.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.kedou.sdk.JuHaoWanSDK;
import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.core.HttpEngineConduits;
import com.kedou.sdk.params.bean.ConfigInfo;

import com.kedou.sdk.ui.activity.UserLoginActivity;
import com.kedou.sdk.ui.view.DialogFactory;
import com.kedou.sdk.utils.ResUtils;
import com.kedou.sdk.utils.ToolsUtils;
import com.kedou.sdk.utils.WL;

public class PhoneLoginFragment extends PhoneVerifyFragment implements View.OnClickListener, TextWatcher {

    private static final String TAG = PhoneLoginFragment.class.getSimpleName();

    private Button mLoginSubmitBtn;
    private EditText mLoginUserPhoneNumberEt;
    private EditText mLoginUserVerifyCodeEt;
    private Button mSendSmsCode;
//    private Button mOneKeyLoginBtn;
    private CheckBox mUserProtocolBox;
    private View mUserProtocolBtn,mPrivateBtn;

    private LoginDialogFragment.OnUserActionListener getOnUserActionListener() {
        Activity activity = getActivity();
        if (activity instanceof LoginDialogFragment.OnUserActionListener) {
            return (LoginDialogFragment.OnUserActionListener) activity;
        }
        return null;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        WL.d(".....","onAttack");
        if (activity instanceof UserLoginActivity) {
            ((UserLoginActivity) activity).setOnPhoneVerifyCodeListener(this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "hnssn_include_viewstub_login_cellphone");
        View contentView = inflater.inflate(resource, null);

        mLoginUserPhoneNumberEt = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_cellphone_number_et"));
        mLoginUserVerifyCodeEt = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_cellphone_verify_code_et"));
        mSendSmsCode = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_cellphone_send_verify_btn"));
        mLoginSubmitBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_cellphone_submit_btn"));
//        mOneKeyLoginBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_login_cellphone_register_btn"));
//        if(XmlUtils.isPutInChannel()&&XmlUtils.isPutInChannel()&&"3.1.12".equals(XmlUtils.getSdkVersionName())){
//            mOneKeyLoginBtn.setVisibility(View.GONE);
//            if(!TextUtils.isEmpty(XmlUtils.getPrivateUrl())){
//                TextView privateText = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_register_private"));
//                privateText.setText(Html.fromHtml("<a href='"+XmlUtils.getPrivateUrl()+"'>隐私协议</a>)"));
//                privateText.setMovementMethod(LinkMovementMethod.getInstance());//激活链接
//            }
//        }else {
//            mOneKeyLoginBtn.setVisibility(View.VISIBLE);
//        }
//        if(XmlUtils.isNeedPrivate()){
//            ((LinearLayout)mUserProtocolBox.getParent()).setVisibility(View.VISIBLE);
//            mUserProtocolBox.setChecked(false);
//            if(!TextUtils.isEmpty(XmlUtils.getPrivateUrl())){
//                TextView privateText = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(), "activity_register_private"));
//                privateText.setText(Html.fromHtml("<a href='"+XmlUtils.getPrivateUrl()+"'>《隐私协议》</a>"));
//                privateText.setMovementMethod(LinkMovementMethod.getInstance());//激活链接
//            }
//        }else{
//            ((LinearLayout)mUserProtocolBox.getParent()).setVisibility(View.GONE);
//            mUserProtocolBox.setChecked(true);
//        }
//        mOneKeyLoginBtn.setVisibility(View.GONE);
        mSendSmsCode.setOnClickListener(this);
        mLoginSubmitBtn.setOnClickListener(this);
//        mOneKeyLoginBtn.setOnClickListener(this);
        mUserProtocolBox = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(),"activity_register_user_protocol_cbox"));
        mUserProtocolBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(),"activity_register_user_protocol_btn"));
        mUserProtocolBtn.setOnClickListener(this);
        mPrivateBtn = contentView.findViewById(ResUtils.getViewIdentifier(getActivity(),"activity_register_private"));
        mPrivateBtn.setOnClickListener(this);
//        mUserProtocolBox.setChecked(HttpEngineApi.getInstance().getEngineConduits().readLoginAgreePrivate());
        mUserProtocolBox.setChecked(false);

        mLoginUserPhoneNumberEt.addTextChangedListener(this);
        mLoginUserVerifyCodeEt.addTextChangedListener(this);
        mLoginUserPhoneNumberEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
                if(keyCode ==  EditorInfo.IME_ACTION_NEXT&&getSendVerifyCodeView().isClickable()){
                    sendPhoneVerifyCode();
                }
                Log.e("OnKeyListener",keyCode+".."+(event==null));
                return false;
            }
        });

        mLoginUserVerifyCodeEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_DONE&&mLoginSubmitBtn.isEnabled()){
                    submitUserLoginInfoByCellphone();
                }
                Log.e("CodeEtOnKeyListener",actionId+".."+(event==null));
                return false;
            }
        });

        onInitData();

        return contentView;
    }

    private void onInitData() {
        HttpEngineConduits wanSDKDataDao = HttpEngineApi.getInstance().getEngineConduits();
        String cellphone = wanSDKDataDao.readLastLoginPhoneNumber();
        if (!TextUtils.isEmpty(cellphone)) {
            mLoginUserPhoneNumberEt.setText(cellphone);
            mLoginUserPhoneNumberEt.setSelection(cellphone.length());
        }
    }

    @Override
    protected Button getSendVerifyCodeView() {
        return mSendSmsCode;
    }

    @Override
    protected EditText getEditorVerifyCodeView() {
        return mLoginUserVerifyCodeEt;
    }

    @Override
    public void onClick(View view) {
        if (view == mSendSmsCode) {
            sendPhoneVerifyCode();
        }
//        else if (view == mOneKeyLoginBtn) {
//            nextToRegisterActivity();
//        }
        else if (view == mLoginSubmitBtn) {
            if(!mUserProtocolBox.isChecked()){
                Toast.makeText(getActivity(),"请先阅读并同意协议",Toast.LENGTH_SHORT).show();
            }else {
                submitUserLoginInfoByCellphone();
            }
        }else if (view == mUserProtocolBtn){
            ConfigInfo configInfo = JuHaoWanSDK.getInstance().getPlatformConfigInfo();
            String linkUrl = configInfo != null ? configInfo.getAgreement_ur(): DEFAULT_LINK_URL;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TextUtils.isEmpty(linkUrl) ? DEFAULT_LINK_URL : linkUrl)));
        }else if (view == mPrivateBtn){
            ConfigInfo configInfo = JuHaoWanSDK.getInstance().getPlatformConfigInfo();
            String linkUrl = configInfo != null ? configInfo.getPrivacy_url(): DEFAULT_LINK_URL;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TextUtils.isEmpty(linkUrl) ? DEFAULT_LINK_URL : linkUrl)));
        }
    }

    public boolean isChecked(){
        return mUserProtocolBox.isChecked();
    }

    private static final String DEFAULT_LINK_URL = "https://www.baidu.com";
    private void sendPhoneVerifyCode() {
        String phoneNumber = getInputUserCellphone();

        if (TextUtils.isEmpty(phoneNumber)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_telephonenumber"))).show();
            return;
        }

        if (!ToolsUtils.checkCellphone(phoneNumber)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_phonecurrent"))).show();
            return;
        }

        requestVerifyCode(phoneNumber, "get_code_account");
    }

    private void checkSumbitButtonState() {
        String username = getInputUserCellphone();
        String password = getInputUserVerifyCode();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            mLoginSubmitBtn.setEnabled(false);
        } else {
            mLoginSubmitBtn.setEnabled(true);
        }
    }

    public final String getInputUserCellphone() {
        return mLoginUserPhoneNumberEt.getText().toString().trim();
    }

    public final String getInputUserVerifyCode() {
        return mLoginUserVerifyCodeEt.getText().toString().trim();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        checkSumbitButtonState();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void nextToRegisterActivity() {
        LoginDialogFragment.OnUserActionListener listener = getOnUserActionListener();
        if (listener != null) {
            listener.doNextToQuickRegister();
        }
    }

    private void nextToAccountInfosActivity(String cellphone, String verify) {
        LoginDialogFragment.OnUserActionListener listener = getOnUserActionListener();
        if (listener != null) {
            listener.doSubmitCellPhoneNumber(cellphone, verify);
        }
    }

    private void submitUserLoginInfoByCellphone() {
        String phoneNumber = getInputUserCellphone();
        String verifyCode = getInputUserVerifyCode();

        if (TextUtils.isEmpty(phoneNumber)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_telephonenumber"))).show();
            return;
        }

        if (!ToolsUtils.checkCellphone(phoneNumber)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_phonecurrent"))).show();
            return;
        }

        if (!ToolsUtils.checkNumber(verifyCode)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(ResUtils.getStringIdentifier(getActivity(), "hnssn_hint_captcha"))).show();
            return;
        }

        nextToAccountInfosActivity(phoneNumber, verifyCode);
    }
}
